package com.example.music_player

import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection

import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.IOException
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(),ServiceConnection {
    val TAG = "MainActivity"
    var binder:MusicService.MusicBinder?=null
    val Channel_ID="my channel"
    val Notification_ID=1
//    val mediaPlayer = MediaPlayer()
//    val musicList = mutableListOf<String>()
//    val musicNameList = mutableListOf<String>()
//    var current = 0
//    var isPause = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
//        mediaPlayer.setOnPreparedListener {
//            it.start()
//        }
//        //自动切换到下一首歌
//        mediaPlayer.setOnCompletionListener {
//            current++
//            if(current>=musicList.size)current=0
//            play()
//        }


        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_MEDIA_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_AUDIO),
                0
            )
        } else {
           startMusicService()
        }


    //进度条滚动
        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(
                seekBar: SeekBar,
                progress: Int,
                fromUser: Boolean) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })
        thread {
            while (binder!=null) {
                Thread.sleep(1000)
                runOnUiThread {
                    seekBar.max = binder!!.duration
                    seekBar.progress = binder!!.currentPosition
                }
            }
        }
    }
    fun startMusicService(){
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
        bindService(intent,this,Context.BIND_AUTO_CREATE)
    }

    fun onPlay(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
    }

    fun onPause(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 2)
        startService(intent)
    }

    fun onStop(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 3)
        startService(intent)
    }

    fun onNext(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 4)
        startService(intent)
    }

    fun onPrev(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 5)
        startService(intent)
    }

//    fun play(){
//        if(musicList.size==0)return
//        val path=musicList[current]
//        mediaPlayer.reset()
//        try{
//            mediaPlayer.setDataSource(path)
//            mediaPlayer.prepareAsync()
//            var textView_mn = findViewById<android.widget.TextView>(R.id.textView_mn)
//            val textView_count = findViewById<android.widget.TextView>(R.id.textView_count)
//            textView_mn.text=musicNameList[current]
//            textView_count.text="${current+1}/${musicList.size}"
//        }catch (e: IOException){
//            e.printStackTrace()
//        }
//    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            getMusicList()
        }
    }
//    @SuppressLint("Range")
//    private fun getMusicList() {
//        val cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
//        if (cursor != null) {
//            while (cursor.moveToNext()) {
//                val musicPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
//                musicList.add(musicPath)
//                val musicName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
//                musicNameList.add(musicName)
//                Log.d(TAG,"getMusicList:$musicPath name: $musicName ")
//            }
//            cursor.close()
//        }
//    }
    override fun onDestroy() {
        super.onDestroy()
        unbindService(this)
//        mediaPlayer.release()
    }

    @SuppressLint("SetTextI18n")
    override fun onServiceConnected(p0: ComponentName?, service: IBinder?) {
        binder=service as MusicService.MusicBinder
        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        val textView_mn = findViewById<android.widget.TextView>(R.id.textView_mn)
        val textView_count = findViewById<android.widget.TextView>(R.id.textView_count)
        thread {
            while (binder!=null) {
                Thread.sleep(1000)
                runOnUiThread {
                    seekBar.max =binder!!.duration
                    seekBar.progress = binder!!.currentPosition
                    textView_mn.text=binder!!.musicName
                    textView_count.text="${binder!!.currentIndex+1}/${binder!!.size}"
                    updateNotification(binder!!.musicName) // 更新通知
                }
            }
        }
    }
    //状态栏显示
    private fun updateNotification(songName: String) {
        // 获取NotificationManager
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // 构建Notification Channel（只在应用第一次启动时创建，通常在onCreate中调）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                Channel_ID,
                "Music Player",
                NotificationManager.IMPORTANCE_LOW
            )
            notificationManager.createNotificationChannel(notificationChannel)
        }

        // 创建Notification.Builder
        val builder = Notification.Builder(this, Channel_ID)
            .setSmallIcon(R.drawable.ic_notification) // 设置小图标
            .setContentTitle("Music Player") // 通知标题
            .setContentText("Playing: $songName") // 通知内容
            .setAutoCancel(true) // 点击后自动消失

        // 创建PendingIntent，点击通知后打开MainActivity
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

        // 设置点击PendingIntent
        builder.setContentIntent(pendingIntent)

        // 构建并发布通知
        val notification = builder.build()
        notificationManager.notify(Notification_ID, notification)
    }
    override fun onServiceDisconnected(p0: ComponentName?) {
        binder=null
    }
}

